package com.example.crudstudy.converter;

import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Date;

@Component
public class StringToDateConverter implements BaseConverter<String, Date> {
    @Override
    public Date convert(String s) {
        if (s.length() < 1) {
            return null;
        }
        DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
                .appendPattern("y-M-d[[ H][:m][:s]]")
                .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                .toFormatter();
        LocalDateTime localDateTime = LocalDateTime.parse(s, dateTimeFormatter);
        Date date = Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
        return date;
    }

    public static void main(String[] args) throws ParseException {
        String s = "2012-12-1";
        DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
                .appendPattern("y-M-d[[ H][:m][:s]]")
                .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                .toFormatter();
        LocalDateTime localDateTime = LocalDateTime.parse(s, dateTimeFormatter);
        Date date = Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
        System.out.println(date);
    }
}
